<template>
  <view class="content">
    <uv-tabs :list="tabs" @click="tabClick" :current="current"></uv-tabs>

    <view class="list">
      <view class="box" v-for="(item,index) in list" :key="index" @click="toDetails(item)">
        <view class="flex justifyBetween fz14">
          <view class="name">{{item.curriculum_Info.name}}</view>
          <view class="status shrink" :style="statusStyle(item)">{{tabs_format(item)}}</view>
        </view>
        <view class="fz12 orderNo alignCenter justifyBetween flex">
          <view>订单号：{{item.out_trade_no}}</view>
          <view class="price">¥{{item.price}}</view>
        </view>
        <view class="actionBtn flex justifyEnd">
          <view @click.stop="toPay(item)" v-if="item.status==0">
            <uv-button text="继续支付" shape="circle" :customStyle="customStyleBtn"></uv-button>
          </view>
          <view @click.stop="payFinalPayment(item)" v-if="item.status==8">
            <uv-button :text="`支付尾款¥${Number(item.price) - Number(item.signUpPrice)}`" shape="circle" :customStyle="customStyleBtn"></uv-button>
          </view>
          <view class="btn" @click.stop="handleClick(item,1)" v-if="item.status==0">
            <uv-button text="取消订单" shape="circle" :customStyle="customStyleBtn"></uv-button>
          </view>
          <view class="btn" @click.stop="handleClick(item,2)" v-if="item.rejectMsg && item.status==1">
            <uv-button text="重新编辑信息" shape="circle" :customStyle="customStyleBtn"></uv-button>
          </view>
          <view v-if="item.invoicing_Info && item.invoicing_Info.ycyy" @click.stop="proxy.$utils.toLink('/packagePages/order/invoiceDetails?out_trade_no='+item.out_trade_no)">
            <uv-text type="error" text="开票失败"></uv-text>
          </view>
          <view class="btn" @click.stop="handleClick(item,3)" v-if="canInvoice(item)">
            <uv-button text="开票" shape="circle" :customStyle="customStyleBtn" color="#4196A3"></uv-button>
          </view>
          <view @click.stop="proxy.$utils.toLink('/packagePages/order/invoiceDetails?out_trade_no='+item.out_trade_no)" v-else-if="item.invoicing_Info && item.invoicing_Info.status == 2">
            <uv-button text="查看发票" shape="circle" customTextStyle="color: #4196A3;" :customStyle="customStyleBtn" color="#F7F7F7"></uv-button>
          </view>
        </view>
        <uv-divider text=""></uv-divider>
      </view>
    </view>

    <uv-empty mode="order" v-if="list.length==0"></uv-empty>

    <getPhonePop ref="getPhonePopRef"></getPhonePop>
  </view>
</template>

<script setup lang="ts">
import getPhonePop from "@/components/main/getPhonePop.vue";
const { proxy } = getCurrentInstance();
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();

let params = ref({
  pageIndex: 1,
  pageSize: 10,
  status: null,
  type: null,
});
let tabs = ref([
  { name: "全部", value: null },
  { name: "未支付", value: 0 },
  { name: "已取消", value: 6 },
  { name: "待审核", value: 1 },
  { name: "报名成功", value: 2 },
  { name: "已退款", value: 4 },
  { name: "已开票", value: 7 },
  { name: "审核通过", value: 8 },
]);
let current = ref(0);

let list = ref([]);

onLoad(() => {
  getInfo();
});

onShow(() => {
  // #ifdef MP-WEIXIN
  if (!counter.isLogin) instance.refs.getPhonePopRef.open();
  // #endif
});

let customStyleBtn = computed(() => {
  return {
    height: "30px",
  };
});

//是否可以开票
function canInvoice(row) {
  //如果不是报名成功状态，则不能开票
  if (row.status != 2) return false;
  let { invoiceStart, invoiceEnd } = row.curriculum_Info;
  //开票开始时间和结束时间有一个是没有的话，则不能开票
  if (!invoiceStart || !invoiceEnd) return false;
  let now = Date.now();
  let start = proxy.$utils.getTimeFn(invoiceStart);
  let end = proxy.$utils.getTimeFn(invoiceEnd);
  if (now >= start && now <= end) return true;
  return false;
}

async function handleClick(params, num) {
  switch (num) {
    case 1:
      let resp = await proxy.$utils.showModal({
        content: "确认取消该订单?",
      });
      if (!resp) return;
      await proxy.$apis.orderAction({
        type: "update",
        data: { status: 6, orderId: params._id },
      });
      proxy.$utils.showToast("取消成功");
      getInfo();
      break;
    case 2:
      counter.orderDetails = proxy.$utils.deepcopy(params);
      proxy.$utils.toLink(`/packagePages/curriculum/enterUserInfo`);
      break;
    case 3: //开票
      proxy.$utils.toLink(
        `/packagePages/order/invoiceIssuance?_id=${params._id}`
      );
      break;
    default:
      break;
  }
}

function toDetails(item) {
  proxy.$utils.toLink(`/packagePages/order/details?id=${item._id}`);
}

function tabClick(e) {
  current.value = e.index;
  init();
}

function init() {
  list.value = [];
  params.value.status = tabs.value[current.value].value;
  params.value.pageIndex = 1;
  getInfo();
}

function statusStyle(e) {
  let obj = {};
  switch (e.status) {
    case 0:
      obj["color"] = "#F56C6C";
      break;
    case 1:
      if (e.rejectMsg) {
        obj["color"] = "#F46E6E";
      } else {
        obj["color"] = "#3C9CFF";
      }
      break;
    case 2:
      obj["color"] = "#5AC726";
      break;
    case 6:
      obj["color"] = "#F8AE3C";
      break;
    case 4:
      obj["color"] = "#999999";
      break;
    default:
      break;
  }
  return obj;
}

async function getInfo() {
  if (!counter.isLogin) return;

  let { total, rows } = await proxy.$apis.orderAction({
    type: "list",
    data: params.value,
  });
  let arr = proxy.$utils.deepcopy(rows);
  if (rows.length) {
    arr = proxy.$utils.filterArr(arr, rows, "_id");
  }
  list.value = arr;
  console.log("列表", list.value);
}

function tabs_format(e) {
  let index = proxy.$utils.findIndexByField(tabs.value, "value", e.status);
  if (e.status == 1 && e.rejectMsg) return "驳回";
  if (index != -1) return tabs.value[index].name;
}

//支付尾款
async function payFinalPayment(row) {
  try {
    let query = {
      orderId: row._id, //订单id
      balancePay: Number(row.price) - Number(row.signUpPrice), //尾款
    };

    let payType = "H5";
    // #ifdef MP-WEIXIN
    payType = "MP-WEIXIN";
    // #endif
    query["payType"] = payType;

    //尾款订单号
    if (row.balance_out_trade_no)
      query["balance_out_trade_no"] = row.balance_out_trade_no;
    let rek = await proxy.$apis.createOrder(query);
    await proxy.$pay.pay(rek);
    proxy.$utils.showToast("支付成功");
  } catch (error) {
  } finally {
    getInfo();
  }
}

async function toPay(item) {
  try {
    let obj = {
      approvalContent: item.approvalContent,
      curriculum_id: item.curriculum_id, //课程 id
      price: item.price,
      out_trade_no: item.out_trade_no,
    };
    let payType = "H5";
    // #ifdef MP-WEIXIN
    payType = "MP-WEIXIN";
    // #endif
    obj["payType"] = payType;

    //如果有预报名价格，则需要加上
    if (item.signUpPrice) obj["signUpPrice"] = item.signUpPrice;

    let resp = await proxy.$apis.createOrder(obj);
    await proxy.$pay.pay(resp);
    proxy.$utils.showToast("支付成功");
  } catch (error) {
  } finally {
    getInfo();
  }
}
</script>

<style lang="scss" scoped>
.content {
  .list {
    padding: 15px 15px 0;
    .box {
      margin-bottom: 15px;
      .status {
        margin-left: 10px;
      }
      .orderNo {
        color: #999999;
        margin-top: 10px;
        .price {
          color: #f66604;
        }
      }
      .actionBtn {
        margin-top: 10px;
        .btn {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
